package com.xingyang.utils;

import com.xingyang.model.LoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * 著名信仰,愿景：让技术不再难学
 **/
public class JWTUtil {

    /*
    * 主题
    * */
    private  static  final String SUBJECT="xingyang";


    //密钥
    private  static  final String SECRET="xingyang.com";

    //token前缀
    private  static  final String TOKEN_PREFIX="dcloud-link";

    //过期时间
    private  static  final int EXPIRE=1000*60*60*24*7;



    /**
     * 根据用户信息，生成令牌
     *
     * @param user
     * @return
     */
    public static String geneJsonWebToken(LoginUser user) {

        if (user==null){
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("account_no", user.getAccountNo())
                .claim("username", user.getUserName())
                .claim("mail", user.getMail())
                .claim("phone", user.getPhone())
                .claim("auth", user.getAuth())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        token = TOKEN_PREFIX + token;

        return token;
    }



    /**
     * 校验token的方法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {

        try {

            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, "")).getBody();

            return claims;

        } catch (Exception e) {
            return null;
        }

    }

}
